package com.example.controller.user;

import com.example.constant.JwtClaimsConstant;
import com.example.dto.BookDishDTO;
import com.example.dto.CategoryDTO;
import com.example.dto.UserLoginDTO;
import com.example.entity.User;
import com.example.properties.JwtProperties;
import com.example.result.Result;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import com.example.vo.BookDishVO;
import com.example.vo.UserLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@Tag(name = "用户管理")
//@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/user/user/login")
    @Operation(summary = "微信登陆")
    public Result userLogin(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登陆:{}",userLoginDTO.getCode());

        //微信登陆
        User user = userService.wxLogin(userLoginDTO);

        Map<String, Object> claims =new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO build = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(build);
    }

    /**
     *  查询分类
     */
    @GetMapping("/user/category/list")
    @Operation(summary = "查询图书分类")
    public Result getCategory(){
        List<CategoryDTO> categoryDTOList=userService.getCategory();
        log.info("用户端查询图书分类:{}",categoryDTOList);
        return Result.success(categoryDTOList);
    }

    /**
     * 查询每个分类下的所有图书
     */
    @GetMapping("/user/setmeal/list")
    @Operation(summary = "查询每个分类下的所有图书")
    public Result getBookDish(Integer categoryId){

        //构造redis key    dish_分类id
        String key="dish_"+categoryId;

        //查询redis中是否存在数据
        List<BookDishVO> bookDishVOList= (List<BookDishVO>) redisTemplate.opsForValue().get(key);

        if(bookDishVOList!=null && bookDishVOList.size()>0){

            //如果存在，直接使用，无需查询数据库
            return Result.success(bookDishVOList);
        }
        else {

            //如果不存在，查询数据库使用并存入redis
            bookDishVOList = userService.getBookDish(categoryId);
            redisTemplate.opsForValue().set(key, bookDishVOList);
        }
        log.info("用户端查询分类下的所有图书:{}",bookDishVOList);
        return Result.success(bookDishVOList);
    }

}
